<template>
  <div class="recommendations-view">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-container">
        <div class="nav-brand">
          <h2>电影推荐系统</h2>
        </div>
        
        <div class="nav-menu">
          <router-link to="/" class="nav-link">
            首页
          </router-link>
          <router-link to="/movies" class="nav-link">
            电影库
          </router-link>
          <router-link to="/recommendations" class="nav-link" active-class="active">
            推荐
          </router-link>
          <router-link to="/profile" class="nav-link">
            个人中心
          </router-link>
        </div>
        
        <div class="nav-user">
          <span class="user-name">{{ authStore.user?.username }}</span>
          <button @click="handleLogout" class="logout-btn">
            退出
          </button>
        </div>
      </div>
    </nav>
    
    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 页面标题和算法选择 -->
      <div class="page-header">
        <h1>电影推荐</h1>
        <div class="algorithm-selector">
          <label for="algorithm">推荐算法:</label>
          <select
            id="algorithm"
            v-model="selectedAlgorithm"
            @change="handleAlgorithmChange"
            class="algorithm-select"
          >
            <option value="hybrid">混合推荐</option>
            <option value="user_based">基于用户的协同过滤</option>
            <option value="item_based">基于物品的协同过滤</option>
            <option value="content_based">基于内容的推荐</option>
          </select>
          
          <label for="num_recommendations">推荐数量:</label>
          <select
            id="num_recommendations"
            v-model="numRecommendations"
            @change="handleNumChange"
            class="num-select"
          >
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>
      
      <!-- 算法说明 -->
      <div class="algorithm-info">
        <div class="info-card">
          <h3>{{ algorithmInfo.title }}</h3>
          <p>{{ algorithmInfo.description }}</p>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="moviesStore.isLoading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在生成推荐...</p>
      </div>
      
      <!-- 推荐结果 -->
      <div v-else-if="moviesStore.recommendations.length > 0" class="recommendations-section">
        <div class="recommendations-grid">
          <div
            v-for="(recommendation, index) in moviesStore.recommendations"
            :key="recommendation.movie.id"
            class="recommendation-card"
            @click="goToMovie(recommendation.movie.id)"
          >
            <div class="recommendation-rank">
              #{{ (moviesStore.recommendationPagination.currentPage - 1) * moviesStore.recommendationPagination.pageSize + index + 1 }}
            </div>
            
            <div class="movie-info">
              <h3 class="movie-title">{{ recommendation.movie.title }}</h3>
              <p class="movie-year">{{ recommendation.movie.year }}</p>
              
              <div class="movie-genres">
                <span
                  v-for="genre in recommendation.movie.genres"
                  :key="genre.id"
                  class="genre-tag"
                >
                  {{ genre.name }}
                </span>
              </div>
              
              <div class="movie-ratings">
                <div class="rating-item">
                  <span class="rating-label">平均评分:</span>
                  <span class="rating-value average">{{ recommendation.movie.average_rating.toFixed(1) }}</span>
                </div>
                
                <div class="rating-item">
                  <span class="rating-label">预测评分:</span>
                  <span class="rating-value predicted">{{ recommendation.predicted_rating.toFixed(1) }}</span>
                </div>
                
                <div v-if="recommendation.similarity_score > 0" class="rating-item">
                  <span class="rating-label">相似度:</span>
                  <span class="rating-value similarity">{{ (recommendation.similarity_score * 100).toFixed(1) }}%</span>
                </div>
              </div>
              
              <!-- 用户评分状态 -->
              <div class="user-rating-status">
                <span
                  v-if="ratingsStore.hasUserRatedMovie(recommendation.movie.id)"
                  class="rated-indicator"
                >
                  ✓ 已评分: {{ ratingsStore.getUserRatingForMovie(recommendation.movie.id)?.rating }}
                </span>
                <span v-else class="not-rated-indicator">
                  未评分
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页控制 -->
        <div class="pagination">
          <!-- 每页条数选择器 -->
          <div class="page-size-selector">
            <span class="pagination-info">每页显示</span>
            <select
              v-model="currentPageSize"
              @change="handlePageSizeChange"
              :disabled="moviesStore.isLoading"
              class="page-size-select"
            >
              <option :value="5">5条</option>
              <option :value="10">10条</option>
              <option :value="20">20条</option>
            </select>
          </div>
          
          <button
            @click="loadPreviousRecommendationPage"
            :disabled="!moviesStore.hasPreviousRecommendationPage || moviesStore.isLoading"
            class="pagination-btn"
          >
            上一页
          </button>
          
          <!-- 页码选择器 -->
          <div class="page-selector">
            <span class="pagination-info">
              第
            </span>
            <select
              v-model="currentPageInput"
              @change="handlePageChange"
              :disabled="moviesStore.isLoading"
              class="page-select"
            >
              <option
                v-for="page in totalPages"
                :key="page"
                :value="page"
              >
                {{ page }}
              </option>
            </select>
            <span class="pagination-info">
              页 (共 {{ totalPages }} 页)
            </span>
          </div>
          
          <button
            @click="loadNextRecommendationPage"
            :disabled="!moviesStore.hasNextRecommendationPage || moviesStore.isLoading"
            class="pagination-btn"
          >
            下一页
          </button>
        </div>
      </div>
      
      <!-- 无推荐状态 -->
      <div v-else class="no-recommendations">
        <div class="no-recommendations-content">
          <h3>暂无推荐结果</h3>
          <p>可能的原因:</p>
          <ul>
            <li>您还没有为任何电影评分</li>
            <li>评分数据不足以生成准确的推荐</li>
            <li>当前算法无法为您生成推荐</li>
          </ul>
          <div class="action-buttons">
            <router-link to="/movies" class="browse-movies-btn">
              去评分电影
            </router-link>
            <button @click="refreshRecommendations" class="refresh-btn">
              刷新推荐
            </button>
          </div>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-if="moviesStore.error" class="error-message">
        {{ moviesStore.error }}
        <button @click="refreshRecommendations" class="retry-btn">
          重试
        </button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMoviesStore } from '@/stores/movies'
import { useRatingsStore } from '@/stores/ratings'

const router = useRouter()
const authStore = useAuthStore()
const moviesStore = useMoviesStore()
const ratingsStore = useRatingsStore()


// 组件状态
const selectedAlgorithm = ref<'user_based' | 'item_based' | 'content_based' | 'hybrid'>('hybrid')
const numRecommendations = ref('20')

// 分页相关状态
const currentPageInput = ref(1)
const currentPageSize = ref(20)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(moviesStore.recommendationPagination.count / moviesStore.recommendationPagination.pageSize)
})

// 监听分页状态变化
watch(
  () => moviesStore.recommendationPagination.currentPage,
  (newPage) => {
    currentPageInput.value = newPage
  },
  { immediate: true }
)

watch(
  () => moviesStore.recommendationPagination.pageSize,
  (newPageSize) => {
    currentPageSize.value = newPageSize
  },
  { immediate: true }
)

// 算法信息
const algorithmInfo = computed(() => {
  const info = {
    hybrid: {
      title: '混合推荐算法',
      description: '结合多种推荐算法的优势，包括协同过滤和基于内容的推荐，为您提供最准确和多样化的推荐结果。'
    },
    user_based: {
      title: '基于用户的协同过滤',
      description: '根据与您有相似评分偏好的其他用户的喜好来推荐电影。如果其他用户喜欢某部电影，而您还没有看过，系统会推荐给您。'
    },
    item_based: {
      title: '基于物品的协同过滤',
      description: '根据您过去喜欢的电影来推荐相似的电影。如果您喜欢某部电影，系统会推荐其他用户也喜欢的类似电影。'
    },
    content_based: {
      title: '基于内容的推荐',
      description: '根据电影的类型、导演、演员等内容特征来推荐与您喜欢的电影相似的其他电影。'
    }
  }
  
  return info[selectedAlgorithm.value]
})

// 跳转到电影详情
const goToMovie = (movieId: number) => {
  router.push({ name: 'movie-detail', params: { id: movieId } })
}

// 处理登出
const handleLogout = async () => {
  await authStore.logout()
  router.push({ name: 'login' })
}

// 处理算法变更
const handleAlgorithmChange = async () => {
  await fetchRecommendations()
}

// 处理推荐数量变更
const handleNumChange = async () => {
  await fetchRecommendations()
}

// 获取推荐
const fetchRecommendations = async () => {
  try {
    await moviesStore.fetchRecommendations({
      algorithm: selectedAlgorithm.value,
      num: Number(numRecommendations.value),
      page: 1,
      page_size: currentPageSize.value
    })
  } catch (error) {
    console.error('获取推荐失败:', error)
  }
}

// 刷新推荐
const refreshRecommendations = async () => {
  moviesStore.clearError()
  await fetchRecommendations()
}

// 分页相关方法
// 处理页码选择变化
const handlePageChange = async () => {
  try {
    await moviesStore.loadRecommendationPage(currentPageInput.value)
  } catch (error) {
    console.error('跳转页面失败:', error)
  }
}

// 处理每页条数变化
const handlePageSizeChange = async () => {
  try {
    await moviesStore.setRecommendationPageSize(currentPageSize.value)
  } catch (error) {
    console.error('设置每页条数失败:', error)
  }
}

// 加载下一页
const loadNextRecommendationPage = async () => {
  try {
    await moviesStore.loadNextRecommendationPage()
  } catch (error) {
    console.error('加载下一页失败:', error)
  }
}

// 加载上一页
const loadPreviousRecommendationPage = async () => {
  try {
    await moviesStore.loadPreviousRecommendationPage()
  } catch (error) {
    console.error('加载上一页失败:', error)
  }
}

// 页面初始化
onMounted(async () => {
  try {
    // 确保已加载用户评分
    if (ratingsStore.ratings.length === 0) {
      await ratingsStore.fetchRatings()
    }
    
    await fetchRecommendations()
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style scoped>
.recommendations-view {
  min-height: 100vh;
  background-color: #f8fafc;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.nav-brand h2 {
  color: #667eea;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  color: #667eea;
  background-color: #f1f5f9;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  color: #475569;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #dc2626;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.nav-brand h2 {
  color: #667eea;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  color: #667eea;
  background-color: #f1f5f9;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  color: #475569;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #dc2626;
}

/* 主要内容样式 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

/* 页面标题和算法选择 */
.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  color: #1e293b;
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 20px 0;
}

.algorithm-selector {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.algorithm-selector label {
  color: #374151;
  font-weight: 500;
  font-size: 14px;
}

.algorithm-select,
.num-select {
  padding: 8px 12px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.algorithm-select:focus,
.num-select:focus {
  outline: none;
  border-color: #667eea;
}

/* 算法说明 */
.algorithm-info {
  margin-bottom: 30px;
}

.info-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
}

.info-card h3 {
  color: #1e293b;
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.info-card p {
  color: #64748b;
  line-height: 1.6;
  margin: 0;
}

/* 推荐网格 */
.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.recommendation-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.recommendation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.recommendation-rank {
  position: absolute;
  top: -10px;
  right: -10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 14px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.movie-title {
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.movie-year {
  color: #64748b;
  margin: 0 0 15px 0;
  font-size: 14px;
}

.movie-genres {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 15px;
}

.genre-tag {
  background-color: #e2e8f0;
  color: #475569;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.movie-ratings {
  margin-bottom: 15px;
}

.rating-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.rating-label {
  color: #64748b;
  font-size: 14px;
}

.rating-value {
  font-weight: 600;
  font-size: 14px;
}

.rating-value.average {
  color: #f59e0b;
}

.rating-value.predicted {
  color: #10b981;
}

.rating-value.similarity {
  color: #8b5cf6;
}

.user-rating-status {
  text-align: center;
  padding: 8px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
}

.rated-indicator {
  color: #10b981;
  background-color: #ecfdf5;
}

.not-rated-indicator {
  color: #64748b;
  background-color: #f1f5f9;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 80px 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无推荐状态 */
.no-recommendations {
  text-align: center;
  padding: 60px 20px;
}

.no-recommendations-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 40px;
  max-width: 500px;
  margin: 0 auto;
}

.no-recommendations-content h3 {
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.no-recommendations-content p {
  color: #64748b;
  margin: 0 0 15px 0;
  font-size: 16px;
}

.no-recommendations-content ul {
  text-align: left;
  color: #64748b;
  margin: 0 0 30px 0;
  padding-left: 20px;
}

.no-recommendations-content li {
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.browse-movies-btn,
.refresh-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-block;
}

.browse-movies-btn {
  background-color: #667eea;
  color: white;
}

.browse-movies-btn:hover {
  background-color: #5a67d8;
}

.refresh-btn {
  background-color: #64748b;
  color: white;
}

.refresh-btn:hover {
  background-color: #475569;
}

/* 错误状态 */
.error-message {
  background-color: #fee;
  color: #c33;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0;
  text-align: center;
  border: 1px solid #fcc;
}

.retry-btn {
  margin-left: 15px;
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.retry-btn:hover {
  background-color: #dc2626;
}

/* 分页控制样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
}

.pagination-btn {
  padding: 10px 20px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 80px;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #5a67d8;
  transform: translateY(-1px);
}

.pagination-btn:disabled {
  background-color: #cbd5e0;
  cursor: not-allowed;
  transform: none;
}

.pagination-info {
  color: #4a5568;
  font-weight: 500;
  font-size: 14px;
}

.page-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-select {
  padding: 8px 12px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
  min-width: 60px;
}

.page-select:focus {
  outline: none;
  border-color: #667eea;
}

.page-select:disabled {
  background-color: #f1f5f9;
  cursor: not-allowed;
  color: #94a3b8;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-select {
  padding: 8px 12px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
  min-width: 80px;
}

.page-size-select:focus {
  outline: none;
  border-color: #667eea;
}

.page-size-select:disabled {
  background-color: #f1f5f9;
  cursor: not-allowed;
  color: #94a3b8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    flex-direction: column;
    height: auto;
    padding: 15px 20px;
  }
  
  .nav-menu {
    margin: 15px 0;
  }
  
  .algorithm-selector {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .recommendations-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .pagination {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-selector,
  .page-size-selector {
    justify-content: center;
  }
}
</style>